import React, { useState } from 'react';
import { Button, Card, Space, Typography } from 'antd';

const { Text } = Typography;

const LightAnalysisSimulation = ({ onAnalysisResult }) => {
  const [imageData, setImageData] = useState(null);
  const [analyzing, setAnalyzing] = useState(false);

  const analyzeLight = (imageElement) => {
    return new Promise((resolve) => {
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');
      canvas.width = imageElement.width;
      canvas.height = imageElement.height;
      context.drawImage(imageElement, 0, 0);

      const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
      const data = imageData.data;
      let totalBrightness = 0;
      let pixelCount = 0;

      // 计算平均亮度
      for (let i = 0; i < data.length; i += 4) {
        const r = data[i];
        const g = data[i + 1];
        const b = data[i + 2];
        // 使用 HSL 中的 L 值计算亮度
        const brightness = (Math.max(r, g, b) + Math.min(r, g, b)) / 2;
        totalBrightness += brightness;
        pixelCount++;
      }

      const averageBrightness = totalBrightness / pixelCount;
      resolve(averageBrightness);
    });
  };

  const handleAnalyzeClick = async () => {
    if (!imageData) return;

    setAnalyzing(true);
    try {
      const brightness = await analyzeLight(imageData);
      const suggestions = [];

      // 根据亮度值给出建议
      if (brightness < 100) {
        suggestions.push('光线不足，建议补光灯亮度调至 80%');
      }
      if (brightness < 50) {
        suggestions.push('环境光线严重不足，建议使用多个补光灯源');
      }
      if (brightness > 200) {
        suggestions.push('光线过强，建议降低补光灯亮度或增加柔光罩');
      }

      // 模拟检测阴影
      // 这里简单模拟，实际应该使用更复杂的图像分析算法
      if (brightness < 150) {
        suggestions.push('检测到明显阴影，建议调整补光灯角度至 45 度');
      }

      onAnalysisResult({
        brightness,
        suggestions,
        colorTemp: 5600, // 模拟色温值
        distribution: Array(20).fill(0).map((_, i) => ({
          brightness: i * 10,
          count: Math.random() * 20
        }))
      });
    } catch (error) {
      console.error('分析失败:', error);
    } finally {
      setAnalyzing(false);
    }
  };

  return (
    <Card title="模拟分析区" style={{ marginBottom: 20 }}>
      <Space direction="vertical" style={{ width: '100%' }}>
        <Button
          type="primary"
          onClick={handleAnalyzeClick}
          loading={analyzing}
          style={{ marginBottom: 16 }}
        >
          分析光线
        </Button>
        <Text type="secondary">
          点击"分析光线"按钮，系统将自动分析图片中的光线情况，并给出专业补光建议
        </Text>
      </Space>
    </Card>
  );
};

export default LightAnalysisSimulation;
